﻿namespace wwm.LeetCodeHelper;

/// <summary>
/// 工具类
/// </summary>
public static class Utils
{
    /// <summary>
    /// 延迟退出
    /// </summary>
    /// <param name="tokenSource"></param>
    /// <returns></returns>
    public static async Task ConsoleDelayExitAsync(CancellationTokenSource tokenSource = null)
    {
        int timeoutSeconds = 3;
        var t = Task.Run(() =>
        {
            while (Console.ReadKey().KeyChar > 0 || timeoutSeconds >= 0)
            {
                tokenSource?.Cancel();
                if (timeoutSeconds <= 0) break;
            }
        });
        int seconds = timeoutSeconds;
        if (tokenSource != null && tokenSource.IsCancellationRequested) return;
        for (int i = seconds; i >= 0; i--)
        {

            if (tokenSource != null && tokenSource.IsCancellationRequested) return;
            Console.CursorLeft = 0;
            Console.Write("等待" + i + "秒");
            try
            {
                _ = t;
                if (tokenSource != null)
                {
                    await Task.Delay(1000, tokenSource.Token);
                }
                else
                {
                    await Task.Delay(1000);
                }
                timeoutSeconds--;
            }
            catch (Exception)
            {
                timeoutSeconds = 0;
            }
        }
    }

    public static void PrintTwoDimensionArray<T>(T[][] board)
    {
        for (int i = 0; i < board.Length; i++)
        {
            for (int j = 0; j < board[i].Length; j++)
            {
                ConsoleHelper.Write(" " + board[i][j] + " ", ConsoleColor.Green);
            }
            Console.WriteLine();
        }
    }

    /// <summary>
    /// 字符串转double
    /// </summary>
    /// <param name="str"></param>
    /// <param name="decimalDigitNum"></param>
    /// <returns></returns>
    public static double ToDouble(this string str, int decimalDigitNum = -1)
    {
        if (string.IsNullOrWhiteSpace(str))
        {
            return 0d;
        }
        double.TryParse(str, out double d);
        if (decimalDigitNum > -1)
        {
            d = Math.Round(d, decimalDigitNum);
        }
        return d;
    }


    /// <summary>
    /// 对象转成json
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="o"></param>
    /// <param name="writeIndented"></param>
    /// <returns></returns>
    public static string ToJson<T>(this T o, bool writeIndented = false) where T : class
    {
        if (o == null) return "null";
        return JsonSerializer.Serialize(o, new JsonSerializerOptions()
        {
            MaxDepth = 10,
            AllowTrailingCommas = true,
            WriteIndented = writeIndented,
        });
    }
}